package com.adou.jdbc;

import java.sql.*;

/**
 * @description:JDBC用户登录
 * @author:
 * @version: JDBCDemo.java v 0.1
 * @date: 2023.04.01
 */
public class JDBCDemo7 {
    public static void main(String[] args) throws Exception {
//        method1();
        method2();

    }

    // 注入
    private static void method2() throws ClassNotFoundException, SQLException {
        // 1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 2.获取连接

        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);

        // 接收用户名和密码
//        String name = "dsdsds";
//        String pwd = "'or'1'='1";

        String name = "zhangsan";
        String pwd = "123";

        // 3.sql
        String sql = "select * from tb_user where user_name = ? and pass_word= ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        // 4.设置参数
        preparedStatement.setString(1,name);
        preparedStatement.setString(2,pwd);

        System.out.println(sql);
        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        // 6.处理结果
        if(resultSet.next()){
            System.out.println("登录成功");
        } else{
            System.out.println("登录失败");
        }

        // 7.释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }


    private static void method1() throws ClassNotFoundException, SQLException {
        // 1.注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        // 2.获取连接

        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String username = "root";
        String password = "root";
        Connection connection = DriverManager.getConnection(url, username, password);

        // 接收用户名和密码
        String name = "zhangsan";
        String pwd = "123";
        // 3.sql
        String sql = "select * from tb_user where user_name = '"+name+"' and pass_word='"+pwd+"'";


        // 4。获取执行sql对象
        Statement statement = connection.createStatement();

        // 5.执行sql
        ResultSet resultSet = statement.executeQuery(sql);

        // 6.处理结果
        if(resultSet.next()){
            System.out.println("登录成功");
        } else{
            System.out.println("登录失败");
        }

        // 7.释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }

}
